<template>
  <div class="dashboard-builder">
    <McLayout class="container">
      <!-- 头部 -->
      <McHeader 
        :title="'NL2UI Dashboard Builder'" 
        :logoImg="'https://matechat.gitcode.com/logo.svg'"
      >
        <template #operationArea>
          <div class="operations">
            <d-button @click="resetDashboard" bsStyle="common" size="sm">
              重置
            </d-button>
            <d-button @click="exportSchema" bsStyle="primary" size="sm">
              导出配置
            </d-button>
          </div>
        </template>
      </McHeader>

      <!-- 主要内容区域 -->
      <McLayoutContent class="main-content">
        <!-- 聊天界面 -->
        <div class="chat-section">
          <div class="messages-container">
            <div 
              v-for="(msg, idx) in messages" 
              :key="idx"
              :class="['message', msg.from]"
            >
              <McBubble 
                :content="msg.content"
                :align="msg.from === 'user' ? 'right' : 'left'"
                :avatarConfig="getAvatarConfig(msg.from)"
                :loading="msg.loading"
              />

              <!-- 显示生成的UI预览 -->
              <div v-if="msg.schema && msg.from === 'model'" class="schema-preview">
                <div class="preview-header">
                  <span>生成的UI预览</span>
                  <d-button 
                    @click="applySchema(msg.schema)" 
                    bsStyle="primary" 
                    size="xs"
                  >
                    应用此设计
                  </d-button>
                </div>
                <RecursiveRenderer 
                  :schema="{ component: 'd-card', children: msg.schema }"
                  @action="handleUIAction"
                />
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-section">
            <McInput 
              v-model="inputValue"
              :maxLength="2000"
              @submit="handleSubmit"
              placeholder="描述您想要的Dashboard界面..."
            >
              <template #extra>
                <div class="input-actions">
                  <d-button 
                    @click="handleQuickPrompt('生成销售数据报表')"
                    bsStyle="common"
                    size="sm"
                  >
                    销售报表
                  </d-button>
                  <d-button 
                    @click="handleQuickPrompt('生成用户统计面板')"
                    bsStyle="common"
                    size="sm"
                  >
                    用户统计
                  </d-button>
                </div>
              </template>
            </McInput>
          </div>
        </div>

        <!-- 实时预览区域 -->
        <div class="preview-section">
          <div class="preview-container">
            <h3>实时Dashboard预览</h3>
            <div v-if="currentSchema.length === 0" class="empty-state">
              <McIntroduction
                :logoImg="'https://matechat.gitcode.com/logo2x.svg'"
                :title="'NL2UI Dashboard'"
                :subTitle="'开始构建您的Dashboard'"
                :description="description"
              />
              <McPrompt 
                :list="introPrompt.list"
                :direction="introPrompt.direction"
                @itemClick="handleQuickPrompt"
              />
            </div>

            <div v-else class="dashboard-render">
              <RecursiveRenderer 
                v-for="(component, index) in currentSchema"
                :key="component.id || index"
                :schema="component"
                @action="handleUIAction"
              />
            </div>
          </div>
        </div>
      </McLayoutContent>
    </McLayout>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { McLayout, McHeader, McLayoutContent, McBubble, McInput, McIntroduction, McPrompt } from '@matechat/core'
import RecursiveRenderer from './RecursiveRenderer.vue'
import { validateSchema, fallbackUI } from '@/utils/validation'
import { getSystemPrompt, getRefinementPrompt } from '@/utils/promptTemplates'
import { mockLLMResponse } from '@/utils/llmClient'
import type { ComponentSchema, Message } from '@/types'

// 响应式数据
const inputValue = ref('')
const messages = ref<Message[]>([])
const currentSchema = ref<ComponentSchema[]>([])
const isLoading = ref(false)

// 介绍内容
const description = [
  '通过自然语言描述，自动生成Dashboard界面',
  '支持多轮对话修改和优化UI设计',
  '基于DevUI组件库，确保企业级质量标准'
]

const introPrompt = {
  direction: 'horizontal' as const,
  list: [
    {
      value: 'salesReport',
      label: '生成销售数据报表',
      iconConfig: { name: 'icon-chart', color: '#5e7ce0' },
      desc: '包含表格和图表的数据展示'
    },
    {
      value: 'userStats',
      label: '生成用户统计面板', 
      iconConfig: { name: 'icon-user', color: '#3ac295' },
      desc: '用户数据和趋势分析'
    },
    {
      value: 'kpiDashboard',
      label: '生成KPI监控看板',
      iconConfig: { name: 'icon-monitor', color: '#f66f6a' },
      desc: '关键指标数据展示'
    }
  ]
}

// 方法
const getAvatarConfig = (from: 'user' | 'model') => {
  return from === 'user' 
    ? { imgSrc: 'https://matechat.gitcode.com/png/demo/userAvatar.svg' }
    : { imgSrc: 'https://matechat.gitcode.com/logo.svg' }
}

const handleSubmit = async () => {
  if (!inputValue.value.trim()) return

  // 添加用户消息
  const userMessage: Message = {
    from: 'user',
    content: inputValue.value,
    timestamp: Date.now()
  }
  messages.value.push(userMessage)

  const userInput = inputValue.value
  inputValue.value = ''

  // 添加加载中的AI消息
  const aiMessage: Message = {
    from: 'model',
    content: '',
    timestamp: Date.now(),
    loading: true
  }
  messages.value.push(aiMessage)

  isLoading.value = true

  try {
    // 调用LLM（文章中的LLM集成）
    const response = await mockLLMResponse(userInput, currentSchema.value)

    // 验证Schema（文章中的运行时安全性）
    const validation = validateSchema(response.components)

    if (validation.valid && validation.data) {
      aiMessage.schema = validation.data
      aiMessage.content = `已根据您的描述生成UI方案，包含${validation.data.length}个组件`
    } else {
      aiMessage.schema = fallbackUI()
      aiMessage.content = `生成遇到问题，已使用安全备用方案：${validation.error}`
    }

    aiMessage.loading = false
  } catch (error) {
    aiMessage.content = `生成失败：${error instanceof Error ? error.message : '未知错误'}`
    aiMessage.schema = fallbackUI()
    aiMessage.loading = false
  } finally {
    isLoading.value = false
  }
}

const applySchema = (schema: ComponentSchema[]) => {
  currentSchema.value = schema
}

const handleUIAction = (action: string, data?: any) => {
  console.log('UI Action:', action, data)

  // 处理特定的UI动作（文章中的指令式交互）
  switch (action) {
    case 'regenerate':
      handleQuickPrompt('重新生成当前界面')
      break
    case 'modify':
      inputValue.value = `修改当前界面：${data}`
      handleSubmit()
      break
    default:
      // 其他动作可以在这里处理
      break
  }
}

const handleQuickPrompt = (prompt: string) => {
  inputValue.value = prompt
  handleSubmit()
}

const resetDashboard = () => {
  currentSchema.value = []
  messages.value = []
}

const exportSchema = () => {
  const schemaStr = JSON.stringify(currentSchema.value, null, 2)
  const blob = new Blob([schemaStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'dashboard-schema.json'
  a.click()
  URL.revokeObjectURL(url)
}
</script>

<style scoped>
.dashboard-builder {
  height: 100vh;
  background: #f5f5f5;
}

.container {
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.main-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  padding: 20px;
  height: calc(100% - 80px);
}

.chat-section {
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e8e8e8;
  padding-right: 20px;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.message {
  margin-bottom: 16px;
}

.schema-preview {
  margin-top: 8px;
  padding: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  background: #fafafa;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.input-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.preview-section {
  height: 100%;
}

.preview-container {
  height: 100%;
  padding: 16px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
}

.dashboard-render {
  display: grid;
  gap: 16px;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}

.operations {
  display: flex;
  gap: 8px;
}
</style>